package cn.com.connected.base.exception;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URLEncoder;

@Component
public class ErrorLogRobot {

    static Logger logger = LoggerFactory.getLogger(ErrorLogRobot.class);

    private static String DING_DING_ROBOT_URL;

    private static String DING_DING_SECRET;

    private static String APPLICATION_NAME;

    public static String PROFILE;

    @Value("${ding_ding_robot_url:null}")
    public void setDING_DING_ROBOT_URL(String ding_ding_robot_url) {
        DING_DING_ROBOT_URL = ding_ding_robot_url;
    }

    @Value("${ding_ding_secret:null}")
    public void setDingDingSecret(String dingDingSecret) {
        DING_DING_SECRET = dingDingSecret;
    }

    @Value("${spring.profiles.active:null}")
    public void setProfile(String profile) {
        PROFILE = profile;
    }

    @Value("${server.name:'未知服务'}")
    public void setApplicationName(String applicationName) {
        APPLICATION_NAME = applicationName;
    }

    public static void sendError2DingDing(String content){
            if (!PROFILE.equals("prod")){
                return ;
            }
          sendError2DingDing(DING_DING_ROBOT_URL, APPLICATION_NAME+"("+PROFILE+") ："+content);
    }
    /**
     * 发送mq消息到钉钉
     *
     * @param url
     * @param content
     * @return
     * @throws IOException
     */
    private static void sendError2DingDing(String url, String content){
            try {

                Long timestamp = System.currentTimeMillis();

                String stringToSign = timestamp + "\n" + DING_DING_SECRET;
                Mac mac = Mac.getInstance("HmacSHA256");
                mac.init(new SecretKeySpec(DING_DING_SECRET.getBytes("UTF-8"), "HmacSHA256"));
                byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
                String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
                url += ("&timestamp="+timestamp+"&sign="+sign);

                HttpClient httpclient = HttpClients.createDefault();
                HttpPost httppost = new HttpPost(url);
                httppost.addHeader("Content-Type", "application/json; charset=utf-8");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("msgtype", "text");
                JSONObject object = new JSONObject();
                object.put("content", content);
                jsonObject.put("text", object);
                StringEntity se = new StringEntity(jsonObject.toString(), "utf-8");
                httppost.setEntity(se);
                HttpResponse response = httpclient.execute(httppost);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    logger.error("钉钉消息发送失败",response.getStatusLine().getStatusCode());
                }
            } catch (Exception e) {
                logger.error("钉钉消息发送失败",e);
            }
    }

    public static String formatStackTrace(Throwable throwable) {
        if (throwable == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        StackTraceElement[] rtn = throwable.getStackTrace();
        sb.append(throwable.getMessage()).append("\n");
        for (int i = 0; i < rtn.length; i++) {
            sb.append(rtn[i].getClassName()).append(rtn[i].getMethodName()).append(rtn[i].getLineNumber()).append("\n");
            if (i == 10) {
                sb.append("...");
                break;
            }
        }
        return sb.toString();
    }
/*
    public static void main(String[] args) {
        try {
            sendError2DingDing("https://oapi.dingtalk.com/robot/send?access_token=7faf7a1523f4a717c35873d673fdb3fa264b255e46a8c88aa27515732afaaf70","尝试发送1");
            sendError2DingDing("https://oapi.dingtalk.com/robot/send?access_token=743ef880fa09249467c373c4563c6a93c84209e03d0bc6faf3ff233fe3d5cd67","尝试发送2");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
}
